<?php
/**
 * @see Alinks_Form_Element_Abstract
 */
require_once('Alinks/Form/Element/Abstract.php');

/**
 * Represents a form select element
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: Select.php 378 2008-07-03 05:19:31Z sean $
 * @package Alinks_Form
 */
class Alinks_Form_Element_Select extends Alinks_Form_Element_Abstract
{
	/**
	 * The select options
	 *
	 * @var array
	 */
	protected $_options = array();
	
	/**
	 * Constructor
	 *
	 * @param string $name The name of the form element
	 * @param array $args The input arguments
	 * @param string $label The input label
	 * @param array $options The select options
	 */
	public function __construct($name = null, $args = array(), $label = null, array $options = array())
	{
		$this->setName($name);
		$this->setArgs((array)$args);
		$this->setOptions($options);
		$this->setLabel($label);
	}
	
	/**
	 * Sets the select options
	 *
	 * @param array $options The options
	 * @return Alinks_Form_Element_Select
	 */
	public function setOptions(array $options)
	{
		$this->_options = $options;
		return $this;
	}
	
	/**
	 * Returns the select options
	 *
	 * @return array
	 */
	public function getOptions()
	{
		return $this->_options;
		return $this;
	}
	
	/**
	 * Returns the HTML for the form element
	 *
	 * @return string
	 */
	public function getHtml()
	{
		$html = sprintf('<select name="%s" id="%s" %s>',
			$this->getName(), $this->getId(), $this->_argsToString());
		$html .= $this->_optionsToString();
		$html .= '</select>';
		
		return $html;
	} 
	
	/**
	 * Converts the select options to a string
	 *
	 * @return string
	 */
	protected function _optionsToString()
	{
		$options = null;
		foreach($this->_options as $key => $value) {
			$key = htmlspecialchars($key);
			$value = htmlspecialchars($value);
			$options .= "<option name=\"$key\"";
			if ($value == $this->_value) {
				$options .= " selected=\"selected\"";
			}
			$options .= ">$value</option>\r\n"; 
		}
		
		return $options;
	}
}